<?php
namespace Wap\Controller;
use Common\Controller\UsersController;
class UserController extends UsersController {

	public function _initialize() {
        parent::_initialize();
		$info = $this->visitor->get();
        $this->assign('info', $info);
    }

	public function info(){
		$do = I('do');
		if(IS_POST && $do='myinfo'){
			$oldpassword = I('old_password');
			$qq = I('qq');
			$email = I('email');
			$mobile = I('mobile');
			$realname = I('realname');
			$address = I('address');
			$passport = $this->_user_server();
            $result = $passport->edit($this->visitor->info['id'], $oldpassword, array('qq'=>$qq,'email'=>$email,'mobile'=>$mobile,'realname'=>$realname,'address'=>$address));
            if ($result) {
				$re = json_encode(array('status' => 1));
				exit($re);
            } else {
				$re = json_encode(array('status' => 0, 'data' => '修改失败'));
				exit($re);
            }
		}
		$this->_config_seo(array(
			'title' =>  '我的资料  — ',
		));
		$this->display('info');
	}

 
    /**
     * 用户登陆
     */
    public function login() {
        $this->visitor->is_login && $this->redirect('user/index');
        if (IS_POST) {
            $username = $this->_post('username', 'trim');
            $password = $this->_post('password', 'trim');
            $remember = $this->_post('remember');
            if (empty($username)) {
                IS_AJAX && $this->ajaxReturn(0, L('please_input').L('password'));
                $this->error(L('please_input').L('username'));
            }
            if (empty($password)) {
                IS_AJAX && $this->ajaxReturn(0, L('please_input').L('password'));
                $this->error(L('please_input').L('password'));
            }
            //连接用户中心
            $passport = $this->_user_server();
            $uid = $passport->auth($username, $password);
            if (!$uid) {
                IS_AJAX && $this->ajaxReturn(0, $passport->get_error());
                $this->error($passport->get_error());
            }
            //登陆
            $this->visitor->login($uid, $remember);

            //登陆完成钩子
            $tag_arg = array('uid'=>$uid, 'uname'=>$username, 'action'=>'login');
            tag('login_end', $tag_arg);
            //同步登陆
            $synlogin = $passport->synlogin($uid);
            if (IS_AJAX) {
                $this->ajaxReturn(1, L('login_successe').$synlogin);
            } else {
                //跳转到登陆前页面（执行同步操作）
                $from = $this->_post('from', 'trim');
				redirect( $from);
                $this->success(L('login_successe').$synlogin, $from);
            }
        } else {
            /* 同步退出外部系统 */
            if (!empty($_GET['synlogout'])) {
                $passport = $this->_user_server();
                $synlogout = $passport->synlogout();
            }
            if (IS_AJAX) {
				$ref = $_SERVER["HTTP_REFERER"];
				 
				if(strpos($ref,'g=Wap')||strpos($ref,'g=wap')){
					$resp = $this->fetch('Dialog:waplogin');
					$this->ajaxReturn(1, '', $resp);
				}
                $resp = $this->fetch('Dialog:waplogin');
                $this->ajaxReturn(1, '', $resp);
            } else {
                //来路
                $from = isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : __APP__;
                $this->assign('from', $from);
                $this->assign('synlogout', $synlogout);
				$this->_config_seo(array(
					'title' =>  '登录 —— ',
				));
                $this->display();
            }
        }
    }

    /**
     * 用户退出
     */
    public function logout() {
        $this->visitor->logout();
        //同步退出
        $passport = $this->_user_server();
        $synlogout = $passport->synlogout();
        //跳转到退出前页面（执行同步操作）
		redirect($_SERVER['HTTP_REFERER']);
        //$this->success(L('logout_successe').$synlogout, U('Index/index'));
    }

    /**
     * 用户绑定
     */
    public function binding() {
        $user_bind_info = object_to_array(cookie('user_bind_info'));
        $this->assign('user_bind_info', $user_bind_info);
        $this->_config_seo();
        $this->display();
    }

    /**
    * 用户注册
    */
    public function register() {
        $this->visitor->is_login && $this->redirect('user/index');
        if (IS_POST) {
            //方式
            $type = $this->_post('type', 'trim', 'reg');
            if ($type == 'reg') {
                //验证
                $agreement = $this->_post('agreement');
                !$agreement && $this->error(L('agreement_failed'));

                $captcha = $this->_post('captcha', 'trim');
                if(session('captcha') != md5($captcha)){
                    $this->error(L('captcha_failed'));
                }
            }
            $username = $this->_post('username', 'trim');
            $email = $this->_post('email','trim');
            $password = $this->_post('password', 'trim');
            $repassword = $this->_post('repassword', 'trim');
            if ($password != $repassword) {
                $this->error(L('inconsistent_password')); //确认密码
            }
            $gender = $this->_post('gender','intval', '0');
            //用户禁止
            $ipban_mod = D('Ipban');
            $ipban_mod->clear(); //清除过期数据
            $is_ban = $ipban_mod->where("(type='name' AND name='".$username."') OR (type='email' AND name='".$email."')")->count();
            $is_ban && $this->error(L('register_ban'));
            //连接用户中心
            $passport = $this->_user_server();
            //注册
            $uid = $passport->register($username, $password, $email, $gender);
            !$uid && $this->error($passport->get_error());
            //第三方帐号绑定
            if (cookie('user_bind_info')) {
                $user_bind_info = object_to_array(cookie('user_bind_info'));
                import("ITK.Itklib.oauth");
                $oauth = new \oauth($user_bind_info['type']);
                $bind_info = array(
                    'itk_uid' => $uid,
					'itk_username' => $username,
                    'keyid' => $user_bind_info['keyid'],
                    'bind_info' => $user_bind_info['bind_info'],
                );
                $oauth->bindByData($bind_info);
                $this->_save_avatar($uid, $user_bind_info['temp_avatar']);
                cookie('user_bind_info', NULL);
            }
            $tag_arg = array('uid'=>$uid, 'uname'=>$username, 'action'=>'register');
            tag('register_end', $tag_arg);
			//邀请注册奖励
			$union_date = array('uid'=>$uid, 'username'=>$username);
			D('User')->union_reg($union_date);
            //登陆
            $this->visitor->login($uid);
            //登陆完成
            $tag_arg = array('uid'=>$uid, 'uname'=>$username, 'action'=>'login');
            tag('login_end', $tag_arg);
            //同步登陆
            $synlogin = $passport->synlogin($uid);
            $this->success(L('register_successe').$synlogin, U('User/index'));
        } else {
            //关闭注册
            if (!C('itk_reg_status')) {
                $this->error(C('itk_reg_closed_reason'));
            }
            $this->_config_seo(array(
				'title' => ' 注册 ——',
			));
            $this->display();
        }
    }

    /**
     * 第三方头像保存
     */
    private function _save_avatar($uid, $img) {
        //获取后台头像规格设置
        $avatar_size = explode(',', C('itk_avatar_size'));
        //会员头像保存文件夹
        $avatar_dir = C('itk_attach_path') . 'avatar/' . avatar_dir($uid);
        !is_dir($avatar_dir) && mkdir($avatar_dir,0777,true);
        //生成缩略图
        $img = C('itk_attach_path') . 'avatar/temp/' . $img;
        foreach ($avatar_size as $size) {
        	import("ITK.ORG.Image");
            \Image::thumb($img, $avatar_dir.md5($uid).'_'.$size.'.jpg', '', $size, $size, true);
        }
        @unlink($img);
    }
    
    /**
     * 用户消息提示 
     */
    public function msgtip() {
        $result = D('UserMsgtip')->get_list($this->visitor->info['id']);
        $this->ajaxReturn(1, '', $result);
    }

    /**
    * 基本信息修改
    */
    public function index() {
        if( IS_POST ){
            foreach ($_POST as $key=>$val) {
            	import("ITK.ORG.Input");
                $_POST[$key] = \Input::deleteHtmlTags($val);
            }
            $data['gender'] = $this->_post('gender', 'intval');
            $data['province'] = $this->_post('province', 'trim');
            $data['city'] = $this->_post('city', 'trim');
            $data['intro'] = $this->_post('intro', 'trim');
            $data['truename'] = $this->_post('truename', 'trim');
            $data['mobile'] = $this->_post('mobile', 'intval');
            $data['telephone'] = $this->_post('telephone', 'trim');
            $data['address'] = $this->_post('address', 'trim');
            $data['qq'] = $this->_post('qq', 'intval');
            $data['wangwang'] = $this->_post('wangwang', 'trim');
            $birthday = $this->_post('birthday', 'trim');
            $birthday = explode('-', $birthday);
            $data['byear'] = $birthday[0];
            $data['bmonth'] = $birthday[1];
            $data['bday'] = $birthday[2];
            if (false !== M('User')->where(array('id'=>$this->visitor->info['id']))->save($data)) {
                $msg = array('status'=>1, 'info'=>L('edit_success'));
            }else{
                $msg = array('status'=>0, 'info'=>L('edit_failed'));
            }
            $this->assign('msg', $msg);
        }
        $info = $this->visitor->get();
// 		$notice = M('Article')->where(array('cate_id'=>'1'))->select();
// 		$this->assign('notice', $notice);
		$this->assign('qday', M('Sign')->getFieldByUid($info['id'],'sign_ucount'));
        $this->assign('info', $info);
        $this->_config_seo(array(
            'title' => '个人中心&nbsp-&nbsp' . C('itk_site_name'),
        ));
        $this->display();
    }

    /**
     * 修改头像
     */
    public function upload_avatar() {
        if (!empty($_FILES['avatar']['name'])) {
            //会员头像规格
            $avatar_size = explode(',', C('itk_avatar_size'));
            //回去会员头像保存文件夹
            $uid = abs(intval($this->visitor->info['id']));
            $suid = sprintf("%09d", $uid);
            $dir1 = substr($suid, 0, 3);
            $dir2 = substr($suid, 3, 2);
            $dir3 = substr($suid, 5, 2);
            $avatar_dir = $dir1.'/'.$dir2.'/'.$dir3.'/';
            //上传头像
            $suffix = '';
            foreach ($avatar_size as $size) {
                $suffix .= '_'.$size.',';
            }
            $result = $this->_upload($_FILES['avatar'], 'avatar/'.$avatar_dir, array(
                'width'=>C('itk_avatar_size'), 
                'height'=>C('itk_avatar_size'),
                'remove_origin'=>true, 
                'suffix'=>trim($suffix, ','),
                'ext' => 'jpg',
            ), md5($uid));
            if ($result['error']) {
                $this->ajaxReturn(0, $result['info']);
            } else {
                $data = __ROOT__.'/data/upload/avatar/'.$avatar_dir.md5($uid).'_'.$size.'.jpg?'.time();
                $this->ajaxReturn(1, L('upload_success'), $data);
            }
        } else {
            $this->ajaxReturn(0, L('illegal_parameters'));
        }
    }



    /**
     * 修改密码
     */
    public function password() {
        if( IS_POST ){
            $password   = $this->_post('password','trim');
            $newpassword = $this->_post('newpassword','trim');
			$repassword = $this->_post('repassword','trim');
            !$newpassword && $this->error(L('no_new_password'));
            $newpassword != $repassword && $this->error(L('inconsistent_password'));
            $passlen = strlen($newpassword);
            if ($passlen < 6 || $passlen > 20) {
                $this->error(L('password_length_error'));
            }
 
            //连接用户中心
            $passport = $this->_user_server();
            $uid = $passport->auth($this->visitor->info['username'], $password);
            if (!$uid) {
                $this->error('原始密码错误');
            }
			
			$data['password'] = md5($newpassword);
			$result = M('User')->where(array('id'=>$this->visitor->info['id']))->save($data);
            if ($result) {
				$this->success(L('edit_password_success'));
            } else {
				$this->error(M('User')->getError());
            }
        }
        $this->_config_seo(array(
            'title' => '修改密码-' . C('itk_site_name'),
        ));
        $this->display();
    }


	public function union(){
		$info					= $this->visitor->get();
		$union_url				= C('itk_site_url').U('Inval/index',array('id'=>$info['id']));
		//exit($union_url);
		$share_url = "{'url':'".$union_url."'}";
		$union['per_visit']		= C('itk_score_rule.union_visit');
		$union['count_visit']	= C('itk_score_rule.union_visit')* C('itk_score_rule.union_visit_nums');
		$union['per_reg']		= C('itk_score_rule.union_reg');
		$union['count_reg']		= C('itk_score_rule.union_reg')*C('itk_score_rule.union_reg_nums');
        
        $this->assign('union', $union);
		$this->assign('union_url', $union_url);
		$this->assign('share_url', $share_url);
        $this->_config_seo(array(
            'title' => '邀请好友访问 -	' . C('itk_site_name'),
        ));

		$this->display();
	}
	/**
	 * 邀请好友
	 */
	public function unionlist() {
		$p = I('p',1);
		$page_size = 20;
		$start = $page_size * ($p - 1) ;
 
        $count = M('Union')->where(array('uid'=>$this->visitor->info['id']))->count('id');
        $pager = $this->_pager($count, $page_size);

		$union['per_visit']		= C('itk_score_rule.union_visit');
		$union['count_visit']	= C('itk_score_rule.union_visit')* C('itk_score_rule.union_visit_nums');
		$union['per_reg']		= C('itk_score_rule.union_reg');
		$union['count_reg']		= C('itk_score_rule.union_reg')*C('itk_score_rule.union_reg_nums');
        
        $this->assign('union', $union);


		$union_list = M('Union')->field('id,uid,username,ip,score,ouid,ousername,add_time')->where(array('uid'=>$this->visitor->info['id']))->limit($start . ',' . $page_size)->order('add_time DESC')->select();
		$this->assign('union_list', $union_list);
		$this->assign('page', $pager->fshow());
		$this->_config_seo(array(
            'title' => L('user_union') . '	-	' . C('itk_site_name'),
        ));
		$this->display();
	}
	
	 
	/**
	 * 查询用户兑换记录
	 */
	 public function gift() {
        $map = array();
        
        $type=I('type','');
        if($type!='')
        	$map['c.isvirtual']=$type;
        else 
        	$type='all';
        $map['a.uid'] = $this->visitor->info['id'];
        $ScoreOrder_mod = M('ScoreOrder');
        $Score_mod = M('ScoreItem');

        $_db=C('DB_PREFIX');
        $order_list = $ScoreOrder_mod->alias("a")->join("{$_db}score_item as b on a.item_id=b.id")->join("{$_db}score_item_cate as c on c.id=b.cate_id")->field("a.*,b.title,b.img,b.price,b.id as gid")->where($map)->order('a.id DESC')->select();
        $this->assign('order_list', $order_list);
        $this->_curr_menu('order');
        $this->_config_seo(array(
            'title' => L('my_gift') . '	-	' . C('itk_site_name'),
        ));
        $this->assign('type',$type);
        $this->display();
    }
	
    /**
     * 兑换详细信息
     */
    public function order(){
    	$id=I('id');
    	if($id=='') return;
    	$map = array();
    	$map['a.uid'] = $this->visitor->info['id'];
    	$map['a.id'] = $id;
    	
    	$ScoreOrder_mod = M('ScoreOrder');

    	$_db=C('DB_PREFIX');
    	$order = $ScoreOrder_mod->alias("a")->join("{$_db}score_item as b on a.item_id=b.id")->field("a.*,b.title,b.img,b.price,b.id as gid,b.coupon_price,b.price")->where($map)->find();

    	$this->assign('order', $order);

    	$this->_config_seo(array(
    		'title' => L('my_gift'). '-'.C('itk_site_name'),
    	));
    	$this->display();
    }
    
	public function mingxi() {
        $map = array();
        $map['uid'] = $this->visitor->info['id'];
        $type=I('type',0);
        //当前积分
   //     $score_total = $this->visitor->get('score');
        $score_total=M('User')->getFieldById($map['uid'] ,'score');
        $ScoreLog_mod = M('ScoreLog');
        $pagesize = 15;
  //      $count = $ScoreLog_mod->where($map)->count('id');
  //      $pager = $this->_pager($count, $pagesize);

//         $this->assign('logs_list', $logs_list);
//         $this->assign('page', $pager->fshow());
        
        $this->_config_seo(array(
            'title' => L('user_score') . ' - ' . C('itk_site_name'),
        ));
        $this->getUserRank($score_total);
        if($type==1){
        	$logs_list = $ScoreLog_mod->field('id,action,score,add_time')->where($map)->limit(20)->order('id DESC')->select();
        	$this->assign('logs_list', $logs_list);
        	$this->display('record');
        }
        else{
        	$this->getUserScoreRank();
        	$this->display();
        }

    }
    
	private function getUserRank($score_total){
		$where['score']=array('GT',$score_total);
		$res=M('User')->where($where)->count();
		$this->assign('curank',$res+1);
	}
    private function getUserScoreRank(){
    	$res = M('User')->order("score desc")->limit(10)->select();
    	$this->assign('userrank',$res);
    }
    
    /**
     * 帐号绑定
     */
    public function bind() {
        //获取已经绑定列表
        $bind_list = M('User_bind')->field('type')->where(array('uid'=>$this->visitor->info['id']))->select();
        $binds = array();
        if ($bind_list) {
            foreach ($bind_list as $val) {
                $binds[] = $val['type'];
            }
        }
        
        //获取网站支持列表
        $oauth_list = $this->oauth_list;
        foreach ($oauth_list as $type => $_oauth) {
            $oauth_list[$type]['isbind'] = '0';
            if (in_array($type, $binds)) {
                $oauth_list[$type]['isbind'] = '1';
            }
        }
        $this->assign('oauth_list', $oauth_list);
        $this->_config_seo(array(
            'title' => L('user_bind') . '	-	' . C('itk_site_name'),
        ));
        $this->display();
    }

	public function like() {
		$p = I('p',1);
		$page_size = 20;
		$start = $page_size * ($p - 1) ;
		
		$ids_list = D('ItemsLike')->field('id,item_id')->limit($start . ',' . $page_size)->where(array('uid'=>$this->visitor->info['id']))->order('id desc')->select();
		$ids=array(); 
		if($ids_list){
			foreach($ids_list as $val){
				$ids[] = $val['item_id'];
				$item_list[$val['item_id']]=$val['item_id'];
				
			}
		}
		if(count($ids) != 0)
		{
			$where['num_iid'] = array('in',$ids);
			$items = D('Items')->field('id,num_iid,title,price,coupon_price,pic_url,likes,status,coupon_start_time,coupon_end_time,shop_type,volume')->where($where)->select();
			$count = D('ItemsLike')->where(array('uid'=>$this->visitor->info['id']))->count();
		}

		unset($item_list);
		$pager = $this->_pager($count, $page_size);
		foreach($items as $item){

			$item_list[$item['id']] = $item;
			$item_list[$item['id']]['class']	= D('Items')->status($item['status'],$item['coupon_start_time'],$item['coupon_end_time']);
		}
		$this->assign('page', $pager->kshow());
		$this->assign('count', $count);
		$this->assign('items', $item_list);
		$this->_config_seo(array(
			'title' =>  '我的喜欢-' . C('itk_site_name'),
    ));
		$this->display();
	}

 

    /**
     * 检测用户
     */
    public function ajax_check() {
        $type = I('type', 'email', 'trim');
        $user_mod = D('User');
        switch ($type) {
            case 'email':
                $email = I('J_email','', 'trim');
                $user_mod->email_exists($email) ? $this->ajaxReturn(0) : $this->ajaxReturn(1);
                break;
            
            case 'username':
                $username = I('J_username','', 'trim');
                $user_mod->name_exists($username) ? $this->ajaxReturn(0) : $this->ajaxReturn(1);
                break;
        }
    }

	/**
	 * 收件箱
	 */
	public function msg(){
		$uid = $this->visitor->info['id'];
		$msg_mod = M('Msg');
		$map=array(
			'fuid'=>$uid,
			'tuid'=>999999,
		);
		if(!IS_AJAX){
			$res = $msg_mod->where($map)->select();
			$this->assign('feeds',$res);
			$this->_config_seo(array('title' => '站内信   -  ',));
			$this->display();
		}else {
			$content = I('content');
			$data['fuid'] = $this->visitor->info['id'];
			$data['fname'] = $this->visitor->info['username'];
			$data['tuid'] = 999999;
			$data['tname'] = 'SYSTEM';
			$data['info'] = $content;
			$data['status'] = 0;
			$data['add_time'] = time();
			$msg_mod->add($data);
			$_r['info']='提交成功';
			$this->ajaxReturn(1,'',$_r);
		}
	}

	/**
	 * 快递
	 */
	public function kuaidi(){
		$this->_config_seo(array('title' => '快递查询   -  ',));
		$this->display();
	}

	public function avatar(){
		$this->display();
	}
 
	/**
	 * 用户自主发布通知
	 */
	public function accept(){
		if(!IS_AJAX) return;
		$_r=array(
			'status'=>0,
			'info'=>'',
		);
		$map['id'] = $this->visitor->info['id'];
		$data['ison']=I('status');
		$res=M('User')->where($map)->save($data);
		if($res!==false)
			$_r['status']=1;
		else 
			$_r['info']='系统异常,请稍后再试';
		$this->ajaxReturn($_r['status'],'',$_r);
	}
	
	/**
	 * 兑换操作
	 * @author Caption Q1674653
	 */
	public function addorder(){
		if(!IS_AJAX) return;
		$data=array(
			'status'=>0,
			'msg'=>'系统异常',
			'url'=>'',
		);
		$uid = $this->visitor->info['id'];
		if($uid==''){
			$data['status']=-1;
			$data['msg']='您还未登录哦';
			$data['url']=U('user/login');
			$this->ajaxReturn(0,'',$data);
		}
		$_pre=C('DB_PREFIX');
		$res=M('ScoreItem')->alias("a")->join("{$_pre}score_item_cate as b on a.cate_id=b.id")->field("a.*,b.isvirtual")->where(array(
			'a.id'=>I('sid'),
		))->find();
		!$res && $this->ajaxReturn(-1,'',$data);
		
		//虚拟物品直接对接成功
		if($res['isvirtual'] == 1){
			$_d=$this->dealGift($res['id'],$res['isvirtual']);
			$code=0;
			if($_d['status']==-1)
				$code=0;
			else 
				$code=1;
		//	var_dump($_d);exit();
			$this->ajaxReturn($code,'',$_d);
		}else{
			$data['status']=0;
			session('is_gift',I('sid'));
			$data['url']=U('User/gift_address',array('id'=>I('sid')));
			//$data['msg']='是否查看兑换记录';
			$this->ajaxReturn(0,'',$data);
		}
	}
	
	/**
	 * 兑换操作处理事情
	 */
	private function dealGift($id,$isvir=0,$data=array()){
		$_r = array(
			'status'=>0,
			'msg'=>'系统异常',
			'url'=>'',			
		);
		$_s = M('ScoreItem');
		$user_mod = M('User');
		$order_mod = D('ScoreOrder');
		$where['id']=$id;
		$item = $_s->where($where)->find();
		if($item==''){
			$_r['status']=-1;
			$_r['msg']= '商品数据不存在,请刷新再试';
			return $_r;
		}
		// 判断时间
		if($item['start_time'] > time()){
			$_r['status']=-1;
			$_r['msg']= '兑换还没到开始时间哦！';
		}
		if($item['end_time'] < time()){
			$_r['status']=-1;
			$_r['msg']='该活动已结束,无法进行兑换！';
		}
		$uid = $this->visitor->info['id'];
		//积分够不？
		$user_score = $user_mod->where(array('id'=>$uid))->getField('score');
		if($user_score < $item['score']){
			$_r['status']=-1;
			$_r['msg']='亲，兑换该商品您的积分不够哦！';
		}
		//限额
		$eced_num = $order_mod->where(array('uid'=>$uid, 'item_id'=>$item['id']))->sum('item_num');
		if ($item['user_num'] && $eced_num + 1 > $item['user_num']) {
			$_r['status']=-1;
			$_r['msg']= sprintf(L('ec_user_maxnum'), $item['user_num']);
		}
		//查看用户是否有默认地址
		if($isvir==0){
			if(!$data['mobile']|| !$data['address']){
				$_r['status']=-1;
				$_r['msg']='亲，请填写地址跟联系方式哦！';
			}		
		}

		//查看是否缺货
		if($item['stock']==0){
			$_r['status']=-1;
			$_r['msg']='抱歉，该商品暂时缺货哦！';
		}
		if($_r['status']==-1)
			return $_r;
		//开始兑换
		$uname = $this->visitor->info['username'];
		$_d = array(
			'uid' => $uid,
			'uname' => $uname,
			'item_id' => $item['id'],
			'item_name' => $item['title'],
			'item_num' => '1',
			'realname' => $data['realname'],
			'mobile' => $data['mobile'],
			'address' => $data['address'],
			'add_time' => time(),
			'order_score' => $item['score'],
		);

		if (false === $order_mod->create($_d)) {
			$_r['status']=-1;
			$_r['msg']='系统异常,请稍后再试';
			return $_r;
		}
		$order_id = $order_mod->add();
		//扣除用户积分并记录日志
		$user_mod->where(array('id'=>$uid))->setDec('score', $item['score']);
		$ScoreLog_mod = D('ScoreLog');
		$ScoreLog_mod->create(array(
			'uid' => $uid,
			'uname' => $uname,
			'action' => 'gift',
			'score' => $item['score']*-1,
		));
		$ScoreLog_mod->add();
		//减少库存和增加兑换数量
		$_s->save(array(
			'id' => $item['id'],
			'stock' => $item['stock'] - 1,
			'buy_num' => $item['buy_num'] + 1,
		));
		
		$_r['msg']='即将跳转至个人兑换记录';
		$_r['url']=U('User/gift');
		return $_r;
	}
	
	/**
	 * ajax处理实物兑换操作
	 */
	public function ajaxDelTrueChange(){
		if(!IS_AJAX) return;
		
		$data['realname']=I('consignee_name');
		$data['mobile']=I('consignee_phone');
		$data['address']=I('consignee_address');
		$_r=$this->dealGift(I('prizeid'),0,$data);
		$code=0;
		if($_r['status']==-1)
			$code==0;
		else
			$code=1;
		$this->ajaxReturn($code,'',$_r);
	}
	
	
	/**
	 * 兑换地址页面
	 */
	public function gift_address(){
		$id=I('id');
		if(session('is_gift')!=$id) return ;
	
		$_pre=C('DB_PREFIX');
		$res=M('ScoreItem')->alias("a")->join("{$_pre}score_item_cate as b on a.cate_id=b.id")->field("a.*,b.isvirtual")->where(array(
				'a.id'=>$id,
		))->find();
		if($res=='') return;
		$uid = $this->visitor->info['id'];
		$_address=M('UserAddress');
		
		$where['uid']=$uid;
		$where['ison']=1;
		$address=$_address->where($where)->find();
		unset($where['ison']);
		$alladdress=$_address->where($where)->order("ison desc")->select();
		$this->assign('alladdress',$alladdress);
		$this->assign('address',$address);
		$this->assign('item',$res);
		$this->display();
	}
	
	/**
	 * 用户管理地址
	 */
	public function maddress(){
		$uid=$this->visitor->info['id'];
		$_address=M('UserAddress');
		$where['uid']=$uid;
		$address=$_address->where($where)->order("ison desc")->select();
		$this->assign('alladdress',$address);
		$this->_config_seo(array(
			'title' =>  '我的地址-' . C('itk_site_name'),
		));
		$this->display();
	}
	
	public function setdefault(){
		if(!IS_AJAX) return;
		
		$_r=array(
			'status'=>0,
			'msg'=>'系统异常',
			'url'=>'',			
		);
		$id=I('id','','intval');
		if($id==0) {
			$_r['status']=-1;
			$this->ajaxReturn(0,'',$_r);
		}
		$uid=$this->visitor->info['id'];
		$_address=M('UserAddress');
		$where['uid']=$uid;
		$_address->where($where)->save(array('ison'=>0));
		$where['id']=$id;
		$_address->where($where)->save(array('ison'=>1));
		
		$_r['msg']='设置成功';
		$this->ajaxReturn(1,'',$_r);
	}
	
	/**
	 * 删除用户地址
	 */
	public function deladdress(){
		if(!IS_AJAX) return;
	
		$_r=array(
			'status'=>0,
			'msg'=>'系统异常',
			'key'=>0,
		);
		$id=I('id','','intval');
		$is_on=I('del_default','','intval');
		if($id==0) {
			$_r['status']=-1;
			$this->ajaxReturn(0,'',$_r);
		}
		
		$uid=$this->visitor->info['id'];
		$_address=M('UserAddress');
		$where['uid']=$uid;
		$where['id']=$id;
		$_address->where($where)->delete();
		//如果删除了默认地址 则随意一个
		if($is_on==1){
			unset($where['id']);
			$res=$_address->where($where)->find();
			if($res){
				$map['id']=$res['id'];
				$_address->where($map)->save(array('ison'=>1));
			}
			$_r['key']=1;
		}
		
		$_r['msg']='删除成功';
		$this->ajaxReturn(1,'',$_r);
	}
	
	
	public function address(){
		if(!IS_AJAX) return;
		$_r=array(
			'status'=>0,
			'msg'=>'',
			'reload'=>0,
		);
		$uid=$this->visitor->info['id'];
		if($uid==''){
			$_r['status']=-1;
			$_r['msg']='您还未登录哦';
			$this->ajaxReturn(0,'',$_r);
		}
		$_address=M('UserAddress');
		$where['uid']=$uid;
		if(($count=$_address->where($where)->count()) >=C('itk_user_max_address')){
			$_r['status']=-1;
			$_r['msg']='您的地址已达上限,不能再加啦';
			$this->ajaxReturn(0,'',$_r);
		}
		
		$where['ison']=1;
		$address=$_address->where($where)->find();
		!$address && $data['ison']=1;
		$data['username']=I('consignee_name');
		$data['phone']=I('consignee_phone');
		$data['address']=I('consignee_address');
		$data['username']=I('consignee_name');
		$data['uid']=$uid;
		$data['add_time']=time();
		
		$res=$_address->add($data);
		if($res){
			$_r['reload']=$data['ison'];
			$_r['msg']='地址保存成功';
		}else{
			$_r['msg']='系统异常';
			$_r['status']=-1;
			$this->ajaxReturn(0,'',$_r);
		}
		$this->ajaxReturn(1,'',$_r);
	}
	
	/**
	 * 修改地址
	 */
	public function ediaddress(){
		if(!IS_AJAX) return;
		$_r=array(
			'status'=>0,
			'msg'=>'',
			'reload'=>0,
		);
		$uid=$this->visitor->info['id'];
		if($uid==''){
			$_r['status']=-1;
			$_r['msg']='您还未登录哦';
			$this->ajaxReturn(0,'',$_r);
		}
		$_address=M('UserAddress');
		$where['uid']=$uid;
		$where['id']=I('id');

		$data['username']=I('consignee_name');
		$data['phone']=I('consignee_phone');
		$data['address']=I('consignee_address');
	
		$res=$_address->where($where)->save($data);
		if($res){
			$_r['reload']=$data['ison'];
			$_r['msg']='地址保存成功';
		}else{
			$_r['msg']='系统异常';
			$_r['status']=-1;
			$this->ajaxReturn(0,'',$_r);
		}
		$this->ajaxReturn(1,'',$_r);
	}
	
	/**
	 * 晒单操作
	 */
	public function share() {
		$appkey=C('itk_weixin_key');
		$appsecret=C('itk_weixin_secret');
		
		$noncestr= t_random(8);
		$_t=time();
		$url= C('itk_wap_url').U('User/share');
		$_sign=getWxSdkSign($appkey,$appsecret,$noncestr,$url,$_t);
		$this->assign('sign',$_sign);
		$this->assign('time',$_t);
		$this->assign('appid',$appkey);
		$this->assign('url',$url);
		$this->assign('noncestr',$noncestr);
		$this->assign('iswx',checkIsWechat()==true?1:0);
		$this->_config_seo(array(
			'title' =>  '晒单发布 -' . C('itk_site_name'),
		));
		$this->display();
	}
	
	public function myshare() {
		$status=I('status',-1);
		$where['uid']= $this->visitor->info['id'];
		if($status!=-1)
			$where['status']=$status;
		$_smod = M('UserShare');
		$shares=$_smod->where($where)->select();
		$this->_config_seo(array(
			'title' =>  '我的晒单 -' . C('itk_site_name'),
		));

		$this->assign('shares',$shares);
		$this->assign('status',$status);
		$this->assign('share_curr','my');
		$this->display();
	}
	
	public function pshare(){
		if(!IS_AJAX) return;
		
		$_r=array(
			'status'=>0,
			'msg'=>'',
			'url'=>'',
		);
		$data['orderid']=I('order');
		$data['uid']=$this->visitor->info['id'];
		$data['price']=I('price');
		$data['pingfen']=I('grade');
		$data['content']=I('evaluation');
		$data['img']=$this->dealUserPhoto(I('img'));
		$data['add_time']=time();
		$_smod=M('UserShare');
		if($_smod->create($data)){
			$res=$_smod->add();
			if(!$res){
				$_r['status']=-1;
				$_r['msg']='系统异常,请稍后再试';
			}
		}else{
			$_r['status']=-1;
			$_r['msg']='系统异常,请稍后再试';			
		}
		$code=1;
		if($_r['status']==-1)
			$code=0;
		$this->ajaxReturn($code,'',$_r);
	}
	
	private function dealUserPhoto($imgs){

		$access_token = S('weixin_access_token');
		$url = "http://file.api.weixin.qq.com/cgi-bin/media/get?access_token={$access_token}&media_id=";
		$imgPath = './data/share/'.date("Y-m-d")."/";
		$_imgPath = '/data/share/'.date("Y-m-d")."/";
		if(!is_dir($imgPath)) mkdirs($imgPath,0777);
		$localimgUrl='';
		$Http = new \Org\Net\Http;
		for($i=0;$i<count($imgs);$i++){
			$_ourl=$url.$imgs[$i];
			$time = time().substr($imgs[$i], 9,3);
			$filename = 'wx_'.$time.'.jpg';   
			$Http::curlDownload($_ourl,$imgPath.$filename);
			$localimgUrl.= $_imgPath.$filename.',';
		}
		$localimgUrl=substr($localimgUrl,0,-1);
		return $localimgUrl;
	}
	
	
}